<!--
 * @Author: Wushiqi
 * @Descripttion: 评论列表
 * @Date: 2020-10-18 16:03:56
 * @LastEditors: Wushiqi
 * @LastEditTime: 2020-10-19 23:17:40
-->
<template>
  <div class="comment-parent">
    <div v-for="(item, key) in commentList" :key="key">
      <div class="comment-item">
        <div class="user-img">
          <img v-if="item.userinfo && item.userinfo.user_img" :src="item.userinfo.user_img" alt />
          <img v-else src="@/assets/default_img.jpg" alt />
        </div>
        <div class="comment-content">
          <p>
            <span v-if="item.userinfo">{{ item.userinfo.name }}</span>
            <span v-else>此用户无姓名</span>
            <span>{{ item.comment_date }}</span>
          </p>
          <div>{{ item.comment_content }}<span class="publish" @click="publishClick(item.comment_id)">回复</span></div>
        </div>
      </div>
      <comment-item style="padding-left:8.333vw;" :commentChild="item.child" @PostPublish="publishClick" />
    </div>
  </div>
</template>

<script>
import commentItem from './commentItem'
export default {
  components: {
    commentItem
  },
  data() {
    return {
      commentList: null
    };
  },
  created() {
    this.commentData();
  },
  methods: {
    async commentData() {
      const res = await this.$http.get("/comment/" + this.$route.params.id);
      if (res.data) {
        this.$emit('commentLength', res.data.length)
      }
      this.commentList = this.changeData(res.data)
    },
    changeData(arr) {
      // 递归调用方法
      function fn(temp) {
        let arr1 = []
        for (let i = 0; i <arr.length; i++) {
          if (arr[i].parent_id === temp) {
            arr[i].child = fn(String(arr[i].comment_id))
            arr1.push(arr[i])
          }
        }
        return arr1
      }
      return fn(null)
    },
    // 点击回复
    publishClick: function(id) {
      this.$emit('publishClick', id)      
    }
  }
};
</script>

<style lang="scss">
.comment-parent {
  padding: 2.778vw 2.778vw;
  >div {
    border-bottom: 0.278vw solid #e7e7e7;
  }
  .comment-item {
    display: flex;
    padding: 2.778vw 0;
    .user-img {
      margin-right: 2.778vw;
      img {
        width: 9.722vw;
        height: 9.722vw;
        border-radius: 50%;
      }
    }
    .comment-content {
      flex: 1;
      p {
        font-size: 3.611vw;
        color: #555;
        display: flex;
        justify-content: space-between;
        margin-bottom: 1.389vw;
      }
      div {
        font-size: 3.611vw;
      }
      .publish {
        position: absolute;
        right: 15px;
        color: red;
      }
    }
  }
}
</style>